package com.xunshibao.http;

import java.io.File;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.util.FileCopyUtils;

public class ZhubajieCssSeeker {
	private DefaultHttpClient client;

	private DefaultHttpClient getClient() {
		if (client == null) {
			client = new DefaultHttpClient();
			HttpHost proxy = new HttpHost("web-proxy.sgp.hp.com", 8080);
			client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					proxy);
		}
		return client;
	}

	@Test
	public void downloadZhubajieCssFiles() throws Exception {
//		String url = "http://s.zbjimg.com/css/auntion.css";
		 String url = "http://s.zbjimg.com/p/zbj/css/style.css";
		HttpEntity entity = getEntity(url);
		String result = EntityUtils.toString(entity, "UTF-8");
		// System.out.println(result);
		// save(result, "p/zbj/css/style.css");
		save(result, "css/auntion.css");
		Set<String> list = parseImg(result, url);
		System.out.println("=======================");
		if (list != null) {
			for (String s : list) {
//				System.out.println(s);
				try {
					saveImg(s);
				} catch(Exception ex) {
					System.out.println(s);
					ex.printStackTrace();
				}
			}
		}
	}
	
	public void saveImg(String url) throws Exception {
		// url = http://s.zbjimg.com/img/pic.png
		// imgFile = img/pic.png
		String imgFile= getImgDir(url);
		
		File img = new File(tmpDir, imgFile);
		if(!img.getParentFile().exists()) {
			img.getParentFile().mkdirs();
		}
		
		HttpEntity entity = getEntity(url);
		if(entity != null) {
			byte[] bytes = EntityUtils.toByteArray(entity);
			FileCopyUtils.copy(bytes, img);
		}
		
	}
	private String getImgDir(String url) {
		// http://s.zbjimg.com/img/pic.png
		url = url.replace("http://", "");
		// url = s.zbjimg.com/img/pic.png;
		return url.substring(url.indexOf("/")+1);
	}
	
	@Test
	public void test4() {
		System.out.println(getImgDir("http://s.zbjimg.com/p/shop/img/dppic1.png"));
	}
	HttpContext localContext = new BasicHttpContext();
	
	public HttpEntity getEntity(String url) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = getClient().execute(httpGet, localContext);
		return response.getEntity();
	}

	File tmpDir = new File("tmp");
	private void save(String content, String filename) throws Exception {
		File file = new File(tmpDir, filename);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		FileWriter writer = new FileWriter(file);
		FileCopyUtils.copy(content, writer);
	}

	String patternStr = ".*?url\\((.*?)\\).*?";

	Pattern ptn = Pattern.compile(patternStr);

	private Set<String> parseImg(String content, String url) {
		String[] lines = content.split("\r\n");

		Set<String> urls = new HashSet<String>();

		Matcher matcher = ptn.matcher(content);
		String u;
		if (lines != null) {
			for (String line : lines) {
				if (!"".equals(line)) {
					matcher = ptn.matcher(line);
					while (matcher.find()) {
						u = getPath(url, matcher.group(1));
						if (u != null) {
							urls.add(u);
						}
					}
				}
			}
		}

		return urls;
	}

	@Test
	public void test3() {
		parseImg(
				".flbt .ft_left a.select i.rcjian{background:url(http://s.zbjimg.com/p/zbj/img/jian.gif) no-repeat; padding-left:23px; display:block}",
				"");
	}

	private String getPath(String url, String pattern) {
//		 System.out.println(pattern);
		// ../img/pic.png
		// http://s.zbjimg.com/css/auntion.css
		// http://s.zbjimg.com/img/pic.png
		if (pattern.startsWith("..")) {
			url = url.substring(0, url.lastIndexOf("/"));
			url = url.substring(0, url.lastIndexOf("/"));
			url = url + pattern.replace("..", "");
			return url;
		} else if ("about:blank".equals(pattern)) {
			return null;
		} else if (pattern.startsWith("http://")) {
			return pattern;
		}
		return null;
	}

	@Test
	public void test2() {
		System.out.println(getPath("http://s.zbjimg.com/css/auntion.css",
				"../img/pic.png"));
	}
}
